package com.gitee.feizns.explore.data_structure.linked_list.singly.getKthFromEnd;

import com.gitee.feizns.explore.data_structure.linked_list.singly.ListNode;

/**
 * @author feizns
 * @since 2020/3/5
 */
public class GetKthFromEnd {

    public static void main(String[] args) {
        ListNode end = getKthFromEnd(create(), 2);
        System.out.println(end.val);
    }

    private static ListNode create() {
        ListNode r = new ListNode(-1);
        r.next = new ListNode(2);
        r.next.next = new ListNode(3);
        return r;
    }

    public static ListNode getKthFromEnd(ListNode head, int k) {
        K = k;
        return recursive(head);
    }

    private static int K;

    private static ListNode recursive(ListNode n) {
        if ( n != null ) {
            ListNode node = recursive(n.next);
            if ( node == null )
                K--;
            else
                return node;
            if ( K == 0 )
                return n;
        }
        return null;
    }

}
